package com.itsv.paint.view;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;



import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
/**
 * url www.johdan.com
 * @author johdan
 *
 */
public class FingerView extends View {

	//杩欎釜handler涓昏鏄负浜嗙粰activity浼狅拷?鏁版嵁
	public Handler dataHandler;
	public Handler getDataHandler() {
		return dataHandler;
	}
	public void setDataHandler(Handler dataHandler) {
		this.dataHandler = dataHandler;
	}
	
	
	FingerMatrix fingerMatrix;  //鐢ㄤ簬璁＄畻瑙︽懜鐭╅樀鍧愭爣
	
	
	
	//鐢ㄤ簬瀵瑰閮╝ctivity璁剧疆鐢荤瑪鐨勫搴斿睘锟�
	public Paint getmPaint() {
		return mPaint;
	}
	public void setmPaint(Paint mPaint) {
		this.mPaint = mPaint;
	}
	
	private static int mWidth;
	private static int mHeight;
	
	public void setScreenSize(int Width,int Height){
		mWidth=Width;
		mHeight=Height;
	
	}

	/****************************/
	//鑳屾櫙棰滆壊
	public static  int color = Color.RED;
	public static  int srokeWidth = 15;
	
	private Bitmap mBitmap;
	private Canvas mCanvas;
	private Path mPath;
	private Paint mBitmapPaint;// 鐢诲竷鐨勭敾锟�
	private Paint mPaint;// 鐪熷疄鐨勭敾锟�
	private float mX, mY;// 涓存椂鐐瑰潗锟�
	private static final float TOUCH_TOLERANCE = 4;

	// 淇濆瓨Path璺緞鐨勯泦锟�鐢↙ist闆嗗悎鏉ユā鎷熸爤
	private static List<DrawPath> savePath;
	// 璁板綍Path璺緞鐨勫锟�
	private DrawPath dp;

	private int screenWidth, screenHeight;// 灞忓箷闀峰

	private class DrawPath {
		public Path path;// 璺緞
		public Paint paint;// 鐢荤瑪
	}
	
	
	private static final int CUT_BITMAP_SEND_TO_ACTIVITY = 1;
	
	public FingerView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
		DisplayMetrics dm = new DisplayMetrics();
		((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);
		init(dm.widthPixels, dm.heightPixels);
	}

	public FingerView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		DisplayMetrics dm = new DisplayMetrics();
		((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);
		init(dm.widthPixels, dm.heightPixels);
	}

	public FingerView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		DisplayMetrics dm = new DisplayMetrics();
		((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);
		init(dm.widthPixels, dm.heightPixels);
	}

//	public FingerView(Context context, int w, int h) {
//		super(context);
//		init(w, h);
//	}

	private void init(int w, int h) {
		screenWidth = w;
		screenHeight = h;

		mBitmap = Bitmap.createBitmap(screenWidth, screenHeight,
				Bitmap.Config.ARGB_8888);
		// 淇濆瓨锟�锟斤拷锟�锟斤拷缁樺埗鍑烘潵鐨勫浘锟�
		mCanvas = new Canvas(mBitmap);

		mBitmapPaint = new Paint(Paint.DITHER_FLAG);
		mPaint = new Paint();
		mPaint.setAntiAlias(true);

		mPaint.setStyle(Paint.Style.STROKE);
		mPaint.setStrokeJoin(Paint.Join.ROUND);// 璁剧疆澶栬竟锟�
		mPaint.setStrokeCap(Paint.Cap.SQUARE);// 褰㈢姸
		mPaint.setStrokeWidth(12);// 鐢荤瑪瀹藉害

		savePath = new ArrayList<DrawPath>();
		
		timer = new Timer(true); //鍒濆鍖杢imer
		
		fingerMatrix=new FingerMatrix();
	}

	@Override
	public void onDraw(Canvas canvas) {
		//canvas.drawColor(color);//鑳屾櫙棰滆壊锛屼笉璁剧疆涓猴拷?鏄庯紝鍚﹀垯鐪嬩笉鍒板悗闈㈢殑鑷畾涔塭dittext锟�
		// 灏嗗墠闈㈠凡缁忕敾杩囧緱鏄剧ず鍑烘潵
		canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
		if (mPath != null) {
			// 瀹炴椂鐨勬樉锟�
			canvas.drawPath(mPath, mPaint);
		}
		
	}

	private void touch_start(float x, float y) {
		mPath.moveTo(x, y);
		mX = x;
		mY = y;
	}

	private void touch_move(float x, float y) {
		float dx = Math.abs(x - mX);
		float dy = Math.abs(mY - y);
		if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
			// 浠巟1,y1鍒皒2,y2鐢讳竴鏉¤礉濉炲皵鏇茬嚎锛屾洿骞虫粦(鐩存帴鐢╩Path.lineTo涔熸槸鍙互锟�
			mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
			mX = x;
			mY = y;
		}
	}

	private void touch_up() {
		mPath.lineTo(mX, mY);
		mCanvas.drawPath(mPath, mPaint);
		// 灏嗕竴鏉″畬鏁寸殑璺緞淇濆瓨涓嬫潵(鐩稿綋浜庡叆鏍堟搷锟�
		savePath.add(dp);
		mPath = null;// 閲嶆柊缃┖
	}

	/**
	 * 鎾ら攢鐨勬牳蹇冿拷?鎯冲氨鏄皢鐢诲竷娓呯┖锟�灏嗕繚瀛樹笅鏉ョ殑Path璺緞锟�锟斤拷锟�锟斤拷绉婚櫎鎺夛紝 閲嶆柊灏嗚矾寰勭敾鍦ㄧ敾甯冧笂闈拷?
	 */
	public void undo() {
		mBitmap = Bitmap.createBitmap(screenWidth, screenHeight,
				Bitmap.Config.ARGB_8888);
		mCanvas.setBitmap(mBitmap);// 閲嶆柊璁剧疆鐢诲竷锛岀浉褰撲簬娓呯┖鐢诲竷
		// 娓呯┖鐢诲竷锛屼絾鏄鏋滃浘鐗囨湁鑳屾櫙鐨勮瘽锛屽垯浣跨敤涓婇潰鐨勯噸鏂板垵濮嬪寲鐨勬柟娉曪紝鐢ㄨ鏂规硶浼氬皢鑳屾櫙娓呯┖鎺夛拷?
		if (savePath != null && savePath.size() > 0) {
			// 绉婚櫎锟�锟斤拷锟�锟斤拷path,鐩稿綋浜庡嚭鏍堟搷锟�
			savePath.remove(savePath.size() - 1);

			Iterator<DrawPath> iter = savePath.iterator();
			while (iter.hasNext()) {
				DrawPath drawPath = iter.next();
				mCanvas.drawPath(drawPath.path, drawPath.paint);
			}
			invalidate();// 鍒锋柊

			/* 鍦ㄨ繖閲屼繚瀛樺浘鐗囩函绮规槸涓轰簡鏂逛究,淇濆瓨鍥剧墖杩涜楠岃瘉 */
			String fileUrl = Environment.getExternalStorageDirectory()
					.toString() + "/android/data/test.png";
			try {
				FileOutputStream fos = new FileOutputStream(new File(fileUrl));
				mBitmap.compress(CompressFormat.PNG, 100, fos);
				fos.flush();
				fos.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	/**
	 * 閲嶅仛鐨勬牳蹇冿拷?鎯冲氨鏄皢鎾ら攢鐨勮矾寰勪繚瀛樺埌鍙﹀锟�锟斤拷闆嗗悎閲岄潰(锟�锟�鐒跺悗浠巖edo鐨勯泦鍚堥噷闈㈠彇鍑烘渶椤剁瀵硅薄锟�鐢诲湪鐢诲竷涓婇潰鍗冲彲锟�
	 */
	public void redo() {
		// 濡傛灉鎾ら攢浣犳噦浜嗙殑璇濓紝閭ｅ氨璇曡瘯閲嶅仛鍚э拷?
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		float x = event.getX();
		float y = event.getY();

		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			if (null != task){ 
				task.cancel();  //灏嗗師浠诲姟浠庨槦鍒椾腑绉婚櫎 
				task = new TimerTask(){
			       public void run() {  
				       Message message = new Message();      
				       message.what = 1;      
				       handler.sendMessage(message); 
			       }  
				 };
			} 

			System.out.println("瑙︽懜鍧愭爣-----====X鍧愭爣:" +x +"----====Y鍧愭爣:"+y);
			if(null == fingerMatrix){
				fingerMatrix =new FingerMatrix();
				fingerMatrix.init(x, y);
			}else{
				fingerMatrix.setX(x);
				fingerMatrix.setY(y);
			}
			
			// 姣忔down涓嬪幓閲嶆柊new锟�锟斤拷Path
			mPath = new Path();
			// 姣忎竴娆¤褰曠殑璺緞瀵硅薄鏄笉锟�锟斤拷锟�
			dp = new DrawPath();
			dp.path = mPath;
			dp.paint = mPaint;
			touch_start(x, y);
			invalidate();
			break;
		case MotionEvent.ACTION_MOVE:
			if (null != task){ 
				task.cancel();  //灏嗗師浠诲姟浠庨槦鍒椾腑绉婚櫎 
				task = new TimerTask(){
			       public void run() {  
				       Message message = new Message();      
				       message.what = 1;      
				       handler.sendMessage(message); 
			       }  
				 };
			} 

			System.out.println("婊戝姩鏃跺潗锟�----====X鍧愭爣:" +x +"----====Y鍧愭爣:"+y);
			if(null != fingerMatrix){
				fingerMatrix.setX(x);
				fingerMatrix.setY(y);
			}
			
			touch_move(x, y);
			invalidate();
			break;
		case MotionEvent.ACTION_UP:
			System.out.println("鎶捣鍧愭爣-----====X鍧愭爣:" +x +"----====Y鍧愭爣:"+y);
			if(null != fingerMatrix){
				fingerMatrix.setX(x);
				fingerMatrix.setY(y);
			}
			
			touch_up();
			invalidate();
			
			if(null!=timer){
				if (null != task){ 
					task.cancel();  //灏嗗師浠诲姟浠庨槦鍒椾腑绉婚櫎 
					task = new TimerTask(){
				       public void run() {  
					       Message message = new Message();      
					       message.what = 1;      
					       handler.sendMessage(message); 
				       }  
					 };
				} 
				timer.schedule(task,400); 
			}
			else{
				timer = new Timer(true);
//				timer.schedule(task,400); 
			}
			break;
		}
		return true;
	}
	
	
	Timer timer;
	Handler handler = new Handler(){  
      public void handleMessage(Message msg) {  
         switch (msg.what) {      
             case CUT_BITMAP_SEND_TO_ACTIVITY:
            	 System.out.println("*********0.handler鍙戞秷鎭憡璇塧ctivity澶勭悊鏁版嵁 *********");
            	 Bitmap tempBitmap=mBitmap;
            	 //1.寰楀埌缁樺埗鐨勫尯鍩熷潗锟�
            	 if(null != fingerMatrix){
            		 float maxX = fingerMatrix.getMaxX();
            		 float minX = fingerMatrix.getMinX();
            		 float maxY = fingerMatrix.getMaxY();
                	 float minY = fingerMatrix.getMinY();
                	 System.out.println("鐭╅樀鐨勫潗鏍囦俊鎭负锟�======maxX:"+maxX+"----====maxY:"+maxY+"----====minX:"+minX+"----====minY:"+minY); 
                	 
                	 int cutMinX = (int) (minX - 15);
                	 int cutMinY = (int) (minY - 15);
                	 int cutMaxX = (int) (maxX + 15);
                	 int cutMaxY = (int) (maxY + 15);
                	 //澶勭悊璁剧疆瑁佸壀浣嶇疆
                	 if(cutMinX<0){
                		 cutMinX=1;
                	 }
                	 if(cutMinY<0){
                		 cutMinY=1;
                	 }
//                	 if(cutMaxX>mWidth){
//                		 cutMaxX=mHeight-1;
//                	 }
//                	 if(cutMaxY>mHeight){
//                		 cutMinX=mHeight-1;
//                	 }
                	 if(cutMaxX>tempBitmap.getWidth()){
                		 cutMaxX=tempBitmap.getWidth()-1;
                	 }
                	 if(cutMaxY>tempBitmap.getHeight()){
                		 cutMaxY=tempBitmap.getHeight()-1;
                	 }

                	 
                	 int width = (int)(cutMaxX-cutMinX);
                	 int height = (int)(cutMaxY-cutMinY);
                	 
                	 tempBitmap = Bitmap.createBitmap(tempBitmap, cutMinX, cutMinY, width, height);  
//                	 tempBitmap = Bitmap.createBitmap(tempBitmap, (int)minX, (int)minY, width, height);  
                	 System.out.println("瑁佸壀bitmap鎴愬姛");
            	 }
            	 //2.閲嶇疆浣嶇疆鐭╅樀淇℃伅
            	 fingerMatrix = null;
            	 
//            	 //杩欓噷鐩墠浼狅拷?鐨勬槸鍏ㄥ睆鐨刡itmap锛屽簲璇ヤ负缁樺埗锟�锟斤拷x,y杞村埌锟�锟斤拷xy杞寸殑鍖哄煙 +锟�锟斤拷绌虹櫧鍖哄煙鐨勫浘锟�
//            	 for(int i=0;i<savePath.size();i++){
//            		 DrawPath  tempDrawPath= savePath.get(i);
//            		 Path tempPath = new Path(); 
//            		 tempPath= tempDrawPath.path;
//            	 }
            	 
            	/* 鍦ㄨ繖閲屼繚瀛樺浘鐗囩函绮规槸涓轰簡鏂逛究,淇濆瓨鍥剧墖杩涜楠岃瘉 */
     			String fileUrl = Environment.getExternalStorageDirectory()
     					.toString() + "/android/data/test111.png";
     			try {
     				FileOutputStream fos = new FileOutputStream(new File(fileUrl));
     				tempBitmap.compress(CompressFormat.PNG, 100, fos);
     				fos.flush();
     				fos.close();
     			} catch (FileNotFoundException e) {
     				e.printStackTrace();
     			} catch (IOException e) {
     				e.printStackTrace();
     			}
            	 
            	 
            	 Message message = new Message();      
		       	 message.what = 3; 
		       	 Bundle data= new Bundle();
		       	 data.putParcelable("bitmap", tempBitmap);
		       	 message.setData(data);
		         dataHandler.sendMessage(message);
            	 renovate();
                 break;     
             case 2:

            	 
            	 break;
              }      
             super.handleMessage(msg);  
         }    
	}; 
	
	
	TimerTask task = new TimerTask(){  
	       public void run() {  
		       Message message = new Message();      
		       message.what = 1;      
		       handler.sendMessage(message); 
	    }  
	 };
	 
	 
	 /**
	  * 鍒濆鍖栨暟鎹苟鍒锋柊灞忓箷
	  */
	 private void renovate(){
		 System.out.println("*********1.鍒濆鍖栨暟鎹苟鍒锋柊灞忓箷 *********");
    	 if (savePath != null && savePath.size() > 0) {
    		 savePath.removeAll(savePath);
    		 mBitmap = Bitmap.createBitmap(screenWidth, screenHeight,Bitmap.Config.ARGB_8888);
    		 mCanvas.setBitmap(mBitmap);
    		 System.out.println("*********2.鍒濆鍖栨暟鎹垚锟�*********");
    	 }
		 invalidate();// 鍒锋柊灞忓箷
		 System.out.println("*********3.鏇存柊灞忓箷鏁版嵁鎴愬姛 *********");
	     if(null!=timer){
	    	 task.cancel();
	     }
	 }
	 
}
